package com.zjuee.web.ledger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjuee.base.bean.Pages;
import com.zjuee.base.bean.response.CommonResultCode;
import com.zjuee.base.dto.common.plan.PlanInfoDto;
import com.zjuee.base.enums.DictionaryType;
import com.zjuee.base.enums.RedisCacheType;
import com.zjuee.base.exception.BaseException;
import com.zjuee.base.utils.ZjueeUtil;
import com.zjuee.core.translation.service.TranslateData;
import com.zjuee.core.translation.utils.CaseUtil;
import com.zjuee.service.PlanService;
import com.zjuee.vo.*;
import com.zjuee.base.model.common.plan.PlanAffairs;
import com.zjuee.base.model.common.plan.PlanCarry;
import com.zjuee.base.model.common.plan.PlanInfo;
import com.zjuee.base.model.common.plan.PlanRegime;
import com.zjuee.web.ledger.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * @author wu liang
 * @since 1.0
 */
@Slf4j
@Service
public class PlanServiceImpl implements PlanService {
    @Resource
    private TranslateData translateData;
    @Resource
    private PlanMapper planMapper;
    @Resource
    private PlanCarryMapper planCarryMapper;
    @Resource
    private PlanDangerMapper planDangerMapper;
    @Resource
    private PlanAffairsMapper planAffairsMapper;
    @Resource
    private PlanHDeviceMapper planHDeviceMapper;
    @Resource
    private PlanMaterialMapper planMaterialMapper;
    @Resource
    private PlanPDeviceMapper planPDeviceMapper;
    @Resource
    private PlanTreatMapper planTreatMapper;
    @Resource
    private PlanSolidMapper planSolidMapper;
    @Resource
    private PlanRegimeMapper planRegimeMapper;


    @Override
    public PlanLoginVo selectBriefInfo(Long bciId, String wpiYear) {
        return planMapper.selectBriefInfo(bciId, wpiYear);
    }

    @Override
    public PlanInfo selectInfoByBciId(Long bciId, String wpiYear) {
        return planMapper.selectinfoBybciid(bciId, wpiYear);
    }

    @Override
    public String getWpiCode(String wpiCode, String wpiYear) {
        String MaxWpiCode = planMapper.findMaxWpiCode("PM" + wpiCode, wpiYear);
        return ZjueeUtil.getWpicode(MaxWpiCode, wpiCode, wpiYear);
    }

    @Override
    public HashMap<String, Object> planAll(Long planId) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        PlanInfo plan = planMapper.selectById(planId);
        map.put("planInfo", plan);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("wpi_id", planId);
        List plancarrylist = handleCarry(planCarryMapper.selectList(queryWrapper));
        map.put("plancarrylist", translateCarry(plancarrylist, "list"));
        List planDangerlist = planDangerMapper.selectList(queryWrapper);
        map.put("planDangerlist", translateDanger(planDangerlist, "list"));
        List planAffairslist = handleAffairs(planAffairsMapper.selectList(queryWrapper));
        map.put("planAffairslist", translateAffairs(planAffairslist, "list"));
        List planHDevicelist = planHDeviceMapper.selectList(queryWrapper);
        map.put("planHDevicelist", planHDevicelist);
        List planMateriallist = planMaterialMapper.selectList(queryWrapper);
        map.put("planMateriallist", planMateriallist);
        List planPDevicelist = planPDeviceMapper.selectList(queryWrapper);
        map.put("planPDevicelist", planPDevicelist);
        List planTreatlist = planTreatMapper.selectList(queryWrapper);
        map.put("planTreatlist", translateTreat(planTreatlist, "list"));
        List planSolidlist = planSolidMapper.selectList(queryWrapper);
        map.put("planSolidlist", translateSolid(planSolidlist, "list"));
        List planRegimelist = planRegimeMapper.selectList(queryWrapper);
        map.put("planRegimelist", handleRegime(planRegimelist));
        return map;
    }

    @Override
    public String commit(Long id) {
        PlanInfo plan = planMapper.selectById(id);
        if (plan == null) {
            throw new BaseException(CommonResultCode.CONSUMER_RESOURCE_EXP, "计划信息错误！");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("wpi_id", id);
        List planPDevicelist = planPDeviceMapper.selectList(queryWrapper);
        if (planPDevicelist.isEmpty()) {
            throw new BaseException(CommonResultCode.CONSUMER_RESOURCE_EXP, "计划生产设备基本信息未填写！");
        }
        List planDangerlist = planDangerMapper.selectList(queryWrapper);
        List planSolidlist = planSolidMapper.selectList(queryWrapper);
        if (planDangerlist.isEmpty() || planSolidlist.isEmpty()) {
            throw new BaseException(CommonResultCode.CONSUMER_RESOURCE_EXP, "废物产生或者收集计划为填写！");
        }
        plan.setWpiAuditStatus(2);
        planMapper.updateById(plan);
        return "提交成功";
    }

    @Override
    public Page<PlanInfoVo> listPagePlanInfo(PlanInfoDto planInfoDto) {
        if (!Optional.ofNullable(planInfoDto.getPage()).isPresent()) {
            planInfoDto.setPage(new Pages());
        }
        Page<PlanInfoVo> page = planMapper.listPagePlanInfo(planInfoDto.getPage().convert(), planInfoDto);
        translate(page.getRecords(), "list");
        return page;
    }

    @Override
    public List<PlanInfo> getPlanInfo(PlanInfo planInfo) {
        if (planInfo == null) {
            return null;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        if (planInfo.getBciId() != null) {
            queryWrapper.eq("bci_id", planInfo.getBciId());
        }
        if (planInfo.getWpiYear() != null) {
            queryWrapper.eq("wpi_year", planInfo.getWpiYear());
        }
        if (planInfo.getWpiAuditStatus() != null) {
            queryWrapper.eq("WPI_AUDIT_STATUS", planInfo.getWpiAuditStatus());
        }
        if (planInfo.getWpiCode() != null) {
            queryWrapper.eq("wpi_code", planInfo.getWpiCode());
        }
        if (planInfo.getWpiGljhid() != null) {
            queryWrapper.eq("WPI_GLJHID", planInfo.getWpiGljhid());
        }
        if (planInfo.getWpiProvinceId() != null) {
            queryWrapper.eq("WPI_PROVINCE_ID", planInfo.getWpiProvinceId());
        }
        if (planInfo.getWpiSourceId() != null) {
            queryWrapper.eq("WPI_SOURCE_ID", planInfo.getWpiSourceId());
        }

        return planMapper.selectList(queryWrapper);
    }

    @Override
    public PlanInfo getPlanInfoById(Long wpiId) {
        return planMapper.selectById(wpiId);
    }


    @Override
    public Long add(PlanInfo planInfo) {
        planMapper.insert(planInfo);
        return planInfo.getId();
    }

    @Override
    public boolean delete(Long id, Long validateId) {
        return false;
    }

    @Override
    public boolean update(PlanInfo type) {
        return false;
    }

    @Override
    public PlanInfo selectById(Long id, Long validateId) {
        return null;
    }

    @Override
    public Page<PlanInfo> list(PlanInfoDto dto) {
        if (!Optional.ofNullable(dto.getPage()).isPresent()) {
            dto.setPage(new Pages());
        }
        QueryWrapper<PlanInfo> PlanInfoWrapper = new QueryWrapper<PlanInfo>();
        PlanInfoWrapper.eq("bci_id", dto.getBciId());
        if (!StringUtils.isBlank(dto.getWpiYear())) {
            PlanInfoWrapper.eq("wpi_year", dto.getWpiYear());
        }
        return planMapper.selectPage(dto.getPage().convert(), PlanInfoWrapper);
    }

    @Override
    public LambdaQueryWrapper<PlanInfo> fuzzyQuery(PlanInfoDto dto) {
        return null;
    }

    public Object translate(Object list, String returnType) {
        Object obj = translateData.
                translateData(list, "planHandle",
                        String.valueOf(RedisCacheType.CITY),
                        String.valueOf(RedisCacheType.AREA),
                        String.valueOf(RedisCacheType.STREET),
                        String.valueOf(DictionaryType.BCI_TYPE.getValue()),
                        String.valueOf(DictionaryType.BCI_CATEGORY.getValue()),
                        String.valueOf(DictionaryType.BPM_STATUS.getValue())
                );
        if (StringUtils.equalsIgnoreCase(returnType, "map")) {
            return obj;
        }
        return CaseUtil.castList(obj, PlanInfoVo.class);
    }

    public Object translateSolid(Object list, String returnType) {
        Object obj = translateData.
                translateData(list, "planSolidHandle",
                        String.valueOf(RedisCacheType.SOLID_BCLASS),
                        String.valueOf(DictionaryType.PB_WASTE_SHAPE5.getValue()));
        if (StringUtils.equalsIgnoreCase(returnType, "map")) {
            return obj;
        }
        return CaseUtil.castList(obj, PlanSolidVo.class);
    }

    public Object translateDanger(Object list, String returnType) {
        Object obj = translateData.
                translateData(list, "planDangerHandle",
                        String.valueOf(DictionaryType.PB_WASTE_FEATURE.getValue()),
                        String.valueOf(RedisCacheType.DANGER_SCLASS));
        if (StringUtils.equalsIgnoreCase(returnType, "map")) {
            return obj;
        }
        return CaseUtil.castList(obj, PlanDangerVo.class);
    }

    public Object translateCarry(Object list, String returnType) {
        Object obj = translateData.
                translateData(list, "planCarryHandle",
                        String.valueOf(RedisCacheType.DISPOSE_TYPE),
                        String.valueOf(RedisCacheType.DISPOSE_STYPE),
                        String.valueOf(DictionaryType.PB_WASTE_MODEL.getValue()),
                        String.valueOf(RedisCacheType.SOLID_TYPE),
                        String.valueOf(RedisCacheType.SOLID_STYPE),
                        String.valueOf(RedisCacheType.DANGER_SCLASS));
        if (StringUtils.equalsIgnoreCase(returnType, "map")) {
            return obj;
        }
        return CaseUtil.castList(obj, PlanCarryVo.class);
    }

    public Object translateAffairs(Object list, String returnType) {
        Object obj = translateData.translateData(list, "planAffairsHandle", String.valueOf(DictionaryType.WPA_TYPE.getValue()));
        if (StringUtils.equalsIgnoreCase(returnType, "map")) {
            return obj;
        }
        return CaseUtil.castList(obj, PlanAffairs.class);
    }

    public Object translateTreat(Object list, String returnType) {
        Object obj = translateData.
                translateData(list, "planTreatHandle",
                        String.valueOf(RedisCacheType.DISPOSE_TYPE),
                        String.valueOf(RedisCacheType.DISPOSE_STYPE),
                        String.valueOf(RedisCacheType.SOLID_TYPE),
                        String.valueOf(RedisCacheType.SOLID_STYPE)
                );
        if (StringUtils.equalsIgnoreCase(returnType, "map")) {
            return obj;
        }
        return CaseUtil.castList(obj, PlanTreatVo.class);
    }

    public List<PlanRegime> handleRegime(List<PlanRegime> regimeList) {
        for (PlanRegime planRegime : regimeList) {
            planRegime.setWprRegulateUrl(handleUrl(planRegime.getWprRegulateUrl()));
            planRegime.setWprBlameUrl(handleUrl(planRegime.getWprBlameUrl()));
            planRegime.setWprSurveyUrl(handleUrl(planRegime.getWprSurveyUrl()));
            planRegime.setWprTrainUrl(handleUrl(planRegime.getWprTrainUrl()));
            planRegime.setWprCrashUrl(handleUrl(planRegime.getWprCrashUrl()));
            planRegime.setWprMarkUrl(handleUrl(planRegime.getWprMarkUrl()));
            planRegime.setWprAcceptUrl(handleUrl(planRegime.getWprAcceptUrl()));
        }

        return regimeList;
    }

    public List<PlanAffairs> handleAffairs(List<PlanAffairs> affairsList) {
        for (PlanAffairs planAffairs : affairsList) {
            planAffairs.setWpaFlowUrl(handleUrl(planAffairs.getWpaFlowUrl()));
            planAffairs.setWpaMeasureUrl(handleUrl(planAffairs.getWpaMeasureUrl()));
        }

        return affairsList;
    }

    public List<PlanCarry> handleCarry(List<PlanCarry> carryList) {
        for (PlanCarry planCarry : carryList) {
            if (planCarry.getWpcDisposeTreaty() == null)
                continue;
            String[] urls = planCarry.getWpcDisposeTreaty().split(",");
            String result = null;
            for (String url : urls) {
                if (result != null) {
                    result = result + "," + handleUrl(url);
                } else {
                    result = handleUrl(url);
                }
            }
            if (",".equals(result)) {
                result = result.substring(0, result.length() - 1);
            }
            planCarry.setWpcDisposeTreaty(result);
        }

        return carryList;
    }

    public String handleUrl(String url) {
        if (url == null)
            return url;
        String[] strs = url.split("/");
        return strs[strs.length - 1];
    }
}
